import { RefObject, useRef, useState, useEffect, useContext } from 'react'
import { Modal, Form, Select, Input, FormInstance, message, Space, Button } from 'antd';
import { AgentSchema, PartySchema } from '@components/schema/caseSchema'
import { checkIdCard } from '@js/identityTest';
import Dictionary, { DictionaryItem } from '@js/dictionary';
import { CaseContext } from '@src/pages/admin/pages/caseDetail/context'
import AutoNameInput from './autoNameInput'
import { awaitWrap, confirmAction } from '@src/assets/js/tool';
import { addAgentRequest, updateAgentRequest, deleteAgentRequest } from './ajax'
const { Item } = Form
const { Option } = Select
const { TextArea } = Input
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 }
}

function getInitialValues (value: AgentSchema | null, caseid: string, type: string, partyList: PartySchema[], agentList: AgentSchema[], licenseTypeList: DictionaryItem[]) {
  if (value) {
    if (value.scope_type === 'string') {
      try {
        value.scope_type = JSON.parse(value.scope_type)
      } catch (e) {
        console.error(e)
      }
    }
    value.partyIndex = value.party.map(li => li.partyid)
    return {
      ...value,
      caseid,
      type
    }
  }
  const freePartyList = getFreeParty(partyList, agentList, type)
  return {
    caseid,
    type,
    name: undefined, // 全称姓名
    license_type: licenseTypeList[0].title, // 证照类型
    license: '', // 证照号
    structure: '', // 所在单位
    address: '', // 详细地址
    mobile: '', // 手机号
    email: '', // 邮箱
    tel: '', // 其他联系方式
    party: freePartyList, // 被代理的当事人
    partyIndex: freePartyList.map(f => f.partyid),
    party_type: type // 代理当事人类型
  }
}

// 获取未被代理的当事人
function getFreeParty (partyList: PartySchema[], agents: AgentSchema[], type: string) {
  const set = new Set()
  const res: Array<{ [k: string]: any }> = []
  agents.forEach(v => {
    v.party.forEach(p => {
      set.add(p.partyid)
    })
  })
  partyList.forEach(p => {
    if (!set.has(p.id)) {
      res.push({
        scope_type: '', // 代理类型
        scope: '', // 代理权限
        type, // 当事人类型
        partyid: p.id
      })
    }
  })
  return res
}

// 验证身份证
function validateLicense (formRef: RefObject<FormInstance>, value: string) {
  const type = formRef.current?.getFieldValue(['license_type'])
  if (type === '身份证' && typeof value === 'string' && value.length) {
    const e = checkIdCard.test(value)
    if (e) {
      return Promise.reject(new Error(e))
    }
  }
  return Promise.resolve()
}

// 改变当事人
function changeParty (v: string[], type: string, partyList: PartySchema[], formRef: RefObject<FormInstance>) {
  const ids = partyList.map(li => li.id)
  const party = v.map(id => {
    const index = ids.indexOf(id)
    const obj = partyList[index]
    return {
      scope_type: '', // 代理类型
      scope: '', // 代理权限
      type, // 当事人类型
      partyid: obj.id
    }
  })
  formRef.current?.setFieldsValue({
    party,
    partyIndex: party.map(p => p.partyid)
  })
}

async function submitHandle (data: { [k: string]: any }, caseid: string, refreshFn: () => void) {
  let fn: (d: any) => Promise<any> = addAgentRequest
  data.caseid = caseid
  delete data.partyIndex
  if (data.subject_type === '自然人') {
    data.legal = ''
  }
  if (data.id) {
    fn = updateAgentRequest
  }
  if (typeof data.license_type === 'object') {
    data.license_type = JSON.stringify(data.license_type)
  }
  if (typeof data.scope_type) {
    data.scope_type = JSON.stringify(data.scope_type)
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(fn(data))
  h()
  if (e === null) {
    refreshFn()
  }
}

async function delHandle (value: AgentSchema, refreshFn: () => void) {
  const hide = message.loading('删除中', 120)
  const [e] = await awaitWrap(deleteAgentRequest(value.id))
  hide()
  if (e === null) {
    refreshFn()
  }
}

interface Props {
  value: AgentSchema | null
  visible: boolean
  type: string
  partyList: PartySchema[]
  agentList: AgentSchema[]
  editable: boolean
  hide: () => void
}

function Main ({ value, visible, type, partyList, agentList, editable, hide }: Props) {
  const c = useContext(CaseContext)
  const formRef = useRef<FormInstance>(null)
  const [licenseTypeList, setLicenseTypeList] = useState<DictionaryItem[]>([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('自然人证件类型')
      .then(() => {
        setLicenseTypeList(d.getList('自然人证件类型'))
      }).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    if (visible) {
      const current = formRef.current
      const d = getInitialValues(value, c.caseid, type, partyList, agentList, licenseTypeList)
      if (current) {
        current.setFieldsValue(d)
      }
    } else {
      const current = formRef.current
      if (current) {
        current.resetFields()
      }
    }
  }, [value, visible, formRef])
  return (
    <div>
      <Modal
        title={value ? (editable ? '修改代理人' : '代理人详情') : '添加代理人'}
        visible={visible}
        onCancel={() => hide()}
        footer={(
          <Space>
            {value && editable && <Button danger onClick={() => { confirmAction('您确定要删除该代理人吗？', () => delHandle(value, () => { c.initCaseDetail(); hide() })) }}>删除</Button>}
            <Button onClick={() => hide()}>取消</Button>
            {editable && <Button type='primary' onClick={() => formRef.current?.submit()}>确定</Button>}
          </Space>
        )}
      >
        <Form ref={formRef} {...layout} onFinish={(d) => { submitHandle(d, c.caseid, () => { c.initCaseDetail(); hide() }) }}>
          <Item name='id' noStyle><span /></Item>
          <Item name='party' noStyle><span /></Item>
          <Item name='party_type' noStyle><span /></Item>
          <Item label={`${type}名称`} name='partyIndex' rules={[{ required: true, message: `${type}不能为空` }]}>
            <Select mode='multiple' onChange={v => changeParty(v, type, partyList, formRef)} placeholder={`请选择${type}`}>
              {partyList.map(li => (
                <Option key={li.id} value={li.id}>{li.name}</Option>
              ))}
            </Select>
          </Item>
          <Item label='代理人姓名' name='name' rules={[{ required: true, message: '代理人姓名不能为空' }]}>
            <AutoNameInput name='代理人' formRef={formRef} type={type} />
          </Item>
          <Item label='证件类型' name='license_type'>
            <Select
              placeholder='请选择证件类型' onChange={e => {
                formRef.current?.setFieldsValue({ license_type: e })
                formRef.current?.validateFields([['license']])
              }}
            >
              {licenseTypeList.map((li, i) => (
                <Option value={li.title} key={i}>{li.title}</Option>
              ))}
            </Select>
          </Item>
          <Item label='证件号码' name='license' rules={[{ validator: (rule: any, value: string) => validateLicense(formRef, value) }]}>
            <Input placeholder='请输入证件号码' />
          </Item>
          <Item label='所在单位' name='structure'>
            <Input placeholder='请输入所在单位' />
          </Item>
          <Item label='地址' name='address' rules={[{ required: true, message: '地址不能为空' }]}>
            <TextArea placeholder='请输入地址' style={{ resize: 'none' }} />
          </Item>
          <Item label='手机号码' name='mobile' rules={[{ pattern: /^1\d{10}$/, message: '手机号码格式不正确' }, { required: true, message: '手机号码不能为空' }]}>
            <Input placeholder='请输入手机号码' maxLength={11} />
          </Item>
          <Item label='邮箱' name='email' rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
            <Input placeholder='请输入邮箱' />
          </Item>
          <Item label='其他联系方式' name='tel'>
            <Input placeholder='请输入其他联系方式' />
          </Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Main
